package csl.blog.client.netty.handler;

import cn.hutool.json.JSONUtil;
import csl.blog.client.netty.NioNettyClient;
import csl.blog.common.base.netty.MessageBo;
import io.netty.channel.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 心跳检测
 * @author chensl
 * @date 2023-04-19 16:25:07
 * @description
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class ClientHeartbeatHandler extends ChannelInboundHandlerAdapter {

    private final NioNettyClient nioNettyClient;

    ClientHeartbeatHandler(NioNettyClient nioNettyClient) {
        this.nioNettyClient = nioNettyClient;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            if (idleStateEvent.state() == IdleState.WRITER_IDLE) {
                log.info("已经30S没有发送消息给服务端");
//                ctx.channel().close();
//                log.warn("客户端已自动关闭连接.");
            }
            MessageBo message = new MessageBo();
            message.setHeartbeat(Boolean.TRUE);
            ctx.writeAndFlush(JSONUtil.toJsonStr(message)).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //如果运行过程中服务端挂了,执行重连机制
//        log.info("start to reconnect netty server");
//        ctx.channel().eventLoop().schedule(() -> nioNettyClient.start(), 3L, TimeUnit.SECONDS);
//        关闭连接
//        ctx.channel().close();
        super.channelInactive(ctx);
    }

}
